package com.lt.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.hjq.toast.Toaster;
import com.lt.app.ResHelper;
import com.lt.common.DebugHelper;
import com.lt.listener.DataServiceListener;

import java.lang.ref.WeakReference;
import java.util.Random;

/**
 * 封装了必要方法
 *
 * @author luotian
 */
public abstract class BaseActivity extends AppCompatActivity
        implements DataServiceListener {

    protected final String TAG = this.getClass().getSimpleName();
    public boolean isShowIng = false;
    protected final int Msg_Base = 10000;
    protected Intent mIntent;

    /**
     * 访问HTTP接口后返回时的回调 </br>
     *
     * @param msg 返回的消息内容
     */
    protected abstract void receiveMessage(Message msg);

    /**
     * 获取布局 ID
     */
    protected abstract View getLayoutView();

    /**
     * 初始化控件
     */
    protected abstract void init();

    protected abstract void initView();

    private static class MyHandler extends Handler {
        WeakReference<BaseActivity> mActivity;

        MyHandler(BaseActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if (mActivity != null || msg == null) {
                BaseActivity theActivity = mActivity.get();
                if (theActivity != null) {
                    theActivity.handleMessage(msg);
                }
            }
        }
    }


    protected Handler _handler = new MyHandler(this);


    protected void handleMessage(Message message) {
        BaseActivity.this.receiveMessage(message);
    }

    @Override
    public void sendMessage(Message message) {
        if (_handler != null) {
            _handler.sendMessage(message);
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        super.onCreate(savedInstanceState);
        if (useFullScreen()) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
            }
            if (Build.VERSION.SDK_INT >= 28) {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
                getWindow().setAttributes(lp);
                /*
                 *刘海屏（异形屏）显示方式提供了三种显示模式：
                 *
                 * // 默认情况，全屏页面不可用刘海区域，非全屏页面可以进行使用
                 * public static final int LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT = 0;
                 *
                 * // 允许页面延伸到刘海区域
                 * public static final int LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES = 1;
                 *
                 * // 不允许使用刘海区域
                 * public static final int LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER = 2;
                 */
            }
        }
        View v = getLayoutView();
        if (v != null) {
            setContentView(v);
            initView();
            init();
        }
        if (isKeepScreenOn()) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        isShowIng = true;
        super.onResume();
    }

    @Override
    protected void onPause() {
        isShowIng = false;
        super.onPause();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
    }

    /**
     * 设置 app 字体不随系统字体设置改变
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        if (res != null) {
            Configuration config = res.getConfiguration();
            if (config != null && config.fontScale != 1.0f) {
                config.fontScale = 1.0f;
                res.updateConfiguration(config, res.getDisplayMetrics());
            }
        }
        return res;
    }

    public void showToast(Object o) {
        String msg;
        if (o instanceof Integer) {
            msg = ResHelper.getString((int) o);
        } else {
            msg = String.valueOf(o);
        }
        Toaster.show(msg);
    }

    protected void log(String str) {
        DebugHelper.e(TAG, str);
    }

    /**
     * 和 setContentView 对应的方法
     */
    public ViewGroup getContentView() {
        return findViewById(Window.ID_ANDROID_CONTENT);
    }

    /**
     * 隐藏软键盘
     */
    public void hideSoftKeyboard() {
        // 隐藏软键盘，避免软键盘引发的内存泄露
        View view = getCurrentFocus();
        if (view != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (manager != null) {
                manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
    }

    /**
     * startActivityForResult 方法优化
     */

    private OnActivityCallback mActivityCallback;
    private int mActivityRequestCode;

    public void startActivityForResult(Class<? extends Activity> clazz, OnActivityCallback
            callback) {
        startActivityForResult(new Intent(this, clazz), null, callback);
    }

    public void startActivityForResult(Intent intent, OnActivityCallback callback) {
        startActivityForResult(intent, null, callback);
    }

    public void startActivityForResult(Intent intent, @Nullable Bundle
            options, OnActivityCallback callback) {
        // 回调还没有结束，所以不能再次调用此方法，这个方法只适合一对一回调，其他需求请使用原生的方法实现
        if (mActivityCallback == null) {
            mActivityCallback = callback;
            // 随机生成请求码，这个请求码必须在 2 的 16 次幂以内，也就是 0 - 65535
            mActivityRequestCode = new Random().nextInt((int) Math.pow(2, 16));
            startActivityForResult(intent, mActivityRequestCode, options);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (mActivityCallback != null && mActivityRequestCode == requestCode) {
            mActivityCallback.onActivityResult(resultCode, data);
            mActivityCallback = null;
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    public interface OnActivityCallback {

        /**
         * 结果回调
         *
         * @param resultCode 结果码
         * @param data       数据
         */
        void onActivityResult(int resultCode, @Nullable Intent data);
    }

    /**
     * @return 是否全屏
     */
    protected boolean useFullScreen() {
        return false;
    }

    /**
     * @return 是否保存屏幕常量
     */
    protected boolean isKeepScreenOn() {
        return false;
    }

}
